package com.hubei.control;

import com.hubei.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 胡向颖
 * @date 2025/6/25-17:51
 * 功能：处理用户删除请求
 */
@WebServlet("/user_delete.action")
public class UserDeleteControl extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String id = request.getParameter("id");
        if (id == null || id.trim().isEmpty()) {
            request.setAttribute("deleteErr", "删除失败：用户ID不能为空");
            request.getRequestDispatcher("./user_list.action").forward(request, response);
            return;
        }
        try {
            int userId = Integer.parseInt(id);
            UserService service = UserService.getInstance();
            int rows = service.deleteUser(userId);
            if (rows > 0) {
                response.sendRedirect("./user_list.action");
            } else {
                request.setAttribute("deleteErr", "删除失败：未找到该用户或删除过程中出现错误");
                request.getRequestDispatcher("./user_list.action").forward(request, response);
            }
        } catch (NumberFormatException e) {
            request.setAttribute("deleteErr", "删除失败：用户ID格式不正确");
            request.getRequestDispatcher("./user_list.action").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("deleteErr", "删除失败：系统错误，请联系管理员");
            request.getRequestDispatcher("./user_list.action").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}